//
//  MainTabBarController.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/10.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit

class MainTabBarController: BaseTabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getMemCentAccountBalance()
        
        // Do any additional setup after loading the view.
        let name1 = NSNotification.Name(rawValue:GOTOHONME)
        NotificationCenter.default.addObserver(self, selector: #selector(notfifica(sender:)), name: name1, object: nil)
        
        let name2 = NSNotification.Name(rawValue:MALL_CHANGE)
        NotificationCenter.default.addObserver(self, selector: #selector(mallnotfifica(sender:)), name: name2, object: nil)
    }
    

    
    
    static func getHomePageDynamic(callback:@escaping (MainTabBarController?) -> Void )  {
        let mallInfo = LocalStorage.getDic(forKey: DEFULT_MALL)
        self.getHomePage(id:mallInfo?.getString("mallID") ?? "") { (tabbarController) in
            callback(tabbarController)
        }
        
    }
    func getHomePage(id:String,callback:@escaping ([String],[UIImage],[UIImage],[UIViewController]) -> Void) {
        API.formRequest(url: .A_HomePage, params: ["mallID":id]) { (result) in
                    if result.success {
                        let sourcesVC = [M_IndexPageVC(),M_CatalogVC(),M_PartIndexVC(),M_CartListVC(),M_UserVC()]
                        let sourceSelctedImages = [UIImage(named: "sye_18")!,UIImage(named: "mulu_24")!,UIImage(named: "paiduihui_26")!,UIImage(named: "guowuche_32")!,UIImage(named: "home_38")!]
                        
                        let sourceNormalImages = [UIImage(named: "sye_23")!,UIImage(named: "mulu_19")!,UIImage(named: "paiduihui_20")!,UIImage(named: "guowuche_21")!,UIImage(named: "home_22")!]
                        
                        var selectedImages = [UIImage]()
                        var normalImages = [UIImage]()
                        
                        
                        let menus = result.data?.getDictionary("data")?.getString("descJson")?.toJSONDictList()
                        
                        if menus?.count == 5 {
                            var titles = [String]()
                            var images = [UIImage]()
                            var vcs = [UIViewController]()
                            
                            for index in 0...4 {
                                if let menu = menus?[index] {
                                    if let openStatus = menu.getInt("openStatus"), let name = menu.getString("name"), let ims = menu.getString("imgs")  {
                                        if openStatus == 1 {
                                            titles.append(name)
                                            vcs.append(sourcesVC[index])
                                            selectedImages.append(sourceSelctedImages[index])
                                            normalImages.append(sourceNormalImages[index])
                                            if let url = URL(string: ims) {
                                                do {
                                                    let data = try Data(contentsOf: url)
                                                    let img = UIImage(data: data)
                                                    images.append(img ?? UIImage())
                                                    
                                                } catch {
                                                    
                                                }
                                            }
                                            
                                        }
                                    }
                                    
                                }
                                
                                
                            }
                            callback(titles,selectedImages,normalImages,vcs)
                            
                            
                        } else {
                            let selctedImages = [UIImage(named: "sye_18")!,UIImage(named: "mulu_24")!,UIImage(named: "paiduihui_26")!,UIImage(named: "guowuche_32")!,UIImage(named: "home_38")!]
                            
                            let normalImages = [UIImage(named: "sye_23")!,UIImage(named: "mulu_19")!,UIImage(named: "paiduihui_20")!,UIImage(named: "guowuche_21")!,UIImage(named: "home_22")!]
                            callback(["首页","目录","派对荟","购物车","我的"],selctedImages,normalImages,[M_IndexPageVC(),M_CatalogVC(),M_PartIndexVC(),M_CartListVC(),M_UserVC()])
                        }
                        
                    } else {
                        let selctedImages = [UIImage(named: "sye_18")!,UIImage(named: "mulu_24")!,UIImage(named: "paiduihui_26")!,UIImage(named: "guowuche_32")!,UIImage(named: "home_38")!]
                        
                        let normalImages = [UIImage(named: "sye_23")!,UIImage(named: "mulu_19")!,UIImage(named: "paiduihui_20")!,UIImage(named: "guowuche_21")!,UIImage(named: "home_22")!]
                        callback(["首页","目录","派对荟","购物车","我的"],selctedImages,normalImages,[M_IndexPageVC(),M_CatalogVC(),M_PartIndexVC(),M_CartListVC(),M_UserVC()])
                    }
                    
                }
    }
    
    private static func getHomePage(id:String,callback:@escaping (MainTabBarController?) -> Void) {
        var vc:MainTabBarController? = nil
        
        API.formRequest(url: .A_HomePage, params: ["mallID":id]) { (result) in
            if result.success {
                //                let menus =  result.data!["navigation"]["descJson"]
                
//                let sourcesTitles = ["首页","目录","派兑荟","购物车","我的"]
                let sourcesVC = [M_IndexPageVC(),M_CatalogVC(),M_PartIndexVC(),M_CartListVC(),M_UserVC()]
                let sourceSelctedImages = [UIImage(named: "sye_18")!,UIImage(named: "mulu_24")!,UIImage(named: "paiduihui_26")!,UIImage(named: "guowuche_32")!,UIImage(named: "home_38")!]
                
                let sourceNormalImages = [UIImage(named: "sye_23")!,UIImage(named: "mulu_19")!,UIImage(named: "paiduihui_20")!,UIImage(named: "guowuche_21")!,UIImage(named: "home_22")!]
                
                var selectedImages = [UIImage]()
                var normalImages = [UIImage]()
                
                
                let menus = result.data?.getDictionary("data")?.getString("descJson")?.toJSONDictList()
                
                if menus?.count == 5 {
                    var titles = [String]()
                    var images = [UIImage]()
                    var vcs = [UIViewController]()
                    
                    for index in 0...4 {
                        if let menu = menus?[index] {
                            if let openStatus = menu.getInt("openStatus"), let name = menu.getString("name"), let ims = menu.getString("imgs")  {
                                if openStatus == 1 {
                                    titles.append(name)
                                    vcs.append(sourcesVC[index])
                                    selectedImages.append(sourceSelctedImages[index])
                                    normalImages.append(sourceNormalImages[index])
                                    if let url = URL(string: ims) {
                                        do {
                                            let data = try Data(contentsOf: url)
                                            let img = UIImage(data: data)
                                            images.append(img ?? UIImage())
                                            
                                        } catch {
                                            
                                        }
                                    }
                                    
                                }
                            }
                            
                        }
                        
                        
                    }
                    vc = MainTabBarController(titles: titles, selectedImageNames: selectedImages, normalImageNames: normalImages, vcList: vcs)
                    //                    vc = MainTabBarController(titles: titles, selectedImageNames: images, normalImageNames: images, vcList: vcs)
                    
                    
                } else {
                    vc = MainTabBarController()
                }
                
                callback(vc)
                
                
                
                
            } else {
                vc = MainTabBarController()
                callback(vc)

                
            }
            
        }
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
    override init(titles: [String], selectedImageNames: [UIImage], normalImageNames: [UIImage], vcList: [UIViewController]) {
        super.init(titles: titles, selectedImageNames: selectedImageNames, normalImageNames: normalImageNames, vcList: vcList)
    }
    
    init(){
        
        let selctedImages = [UIImage(named: "sye_18")!,UIImage(named: "mulu_24")!,UIImage(named: "paiduihui_26")!,UIImage(named: "guowuche_32")!,UIImage(named: "home_38")!]
        
        let normalImages = [UIImage(named: "sye_23")!,UIImage(named: "mulu_19")!,UIImage(named: "paiduihui_20")!,UIImage(named: "guowuche_21")!,UIImage(named: "home_22")!]
        super.init(titles: ["首页","目录","派对荟","购物车","我的"],
                   selectedImageNames: selctedImages,
                   normalImageNames: normalImages,
                   vcList: [M_IndexPageVC(),M_CatalogVC(),M_PartIndexVC(),M_CartListVC(),M_UserVC()])
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //获取积分信息
    func getMemCentAccountBalance() {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .M_GetMemCentAccountBalance, params: params) { (result) in
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    LocalStorage.saveDic(dl, forKey: APIUrl.M_GetMemCentAccountBalance.rawValue)
                }
            }else{
            }
        }
    }
    
    @objc func notfifica(sender:NSNotification) {
        if let i = anyToInt(sender.userInfo?["selIndex"]) { 
            selectedIndex = i
            getMemCentAccountBalance()
        }
    }
    
    @objc func mallnotfifica(sender:NSNotification) {
        let mallInfo = LocalStorage.getDic(forKey: DEFULT_MALL)
        getHomePage(id: mallInfo?.getString("mallID") ?? "", callback: { (titles,selimgs,nolimgs,vcs) in
            self.titles = titles
            self.selectedImageNames = selimgs
            self.normalImageNames = nolimgs
            self.vcList = vcs
            super.viewDidLoad()
        })
    }
}
